package com.qn.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.LocaleResolver;

import java.util.Locale;

/**
 * 获取请求头国际化信息
 * 使用自定义的I18nLocaleResolver替换默认的AcceptHeaderLocaleResolver，重写resolveLocale方法就可以自定义Locale的解析逻辑。
 * <p>
 * 自定义后使用content-language传Locale信息，使用_划分语言个地区。
 * content-language: en_US
 * content-language: zh_CN
 *
 * @author QN
 * @date 2025/01/01
 */
public class I18nLocaleResolver implements LocaleResolver {

    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        String language = httpServletRequest.getHeader("content-language");
        Locale locale = Locale.getDefault();
        if (language != null && !language.isEmpty()) {
            String[] split = language.split("_");
            locale = new Locale.Builder()
                    .setLanguage(split[0])
                    .setRegion(split[1])
                    .build();
        }
        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {

    }
}
